import {env} from "../env/env";
import {getLoginToken, logout, setLoginToken} from "../service/user";
import {showToast} from "./tool";

const wxAccount = wx.getAccountInfoSync()
const {appId} = wxAccount.miniProgram
const urlBase = `${env.host}/uniapp`

let refreshTokenComplete = true
let requestQueues = []

export function request(options) {

    const _ops = {
        header:{
            Authorization: "Bearer " + getLoginToken(),
            appid: appId,
            'uni-platform': 'mp-weixin',
        },
        method:'POST',
        data:{},
        ...options,
    }



    return new Promise(async (resolve, reject) => {

        wx.request({
            url: `${urlBase}${_ops.url}`,
            data: _ops.data,
            header:_ops.header,
            method:_ops.method,
            success: res => {
                if(res.statusCode < 400){
                    const error = res.data.error
                    switch (error) {

                        case 10001:     // 令牌失效，需要刷新令牌
                            refreshToken(options).then(res => {
                                resolve(res)
                            }).catch(err => {
                                reject(err)
                            })
                            break;
                        case 0:
                            resolve(res.data)
                            break;
                        default:
                            showToast(res.data.msg)
                            reject(res.data)

                    }

                }else{
                    showToast("请求接口错误")
                    reject(res)
                }
            },
            fail: res => {
                showToast("请求服务器失败")
                reject(res)
            }
        })
    });
}

export function simpleGet(url, data){
    return request({
        url,
        method:"GET",
        data,
    })
}

export function simplePost(url, data){
    return request({
        url,
        method: "POST",
        data,
    })
}

export function simplePatch(url, data){
    return request({
        url,
        method: "PATCH",
        data,
    })
}

// 刷新令牌
function refreshToken(options){
    return new Promise((resolve, reject) => {
        // 判断是否有正在刷新令牌的请求
        if (refreshTokenComplete){  // 没有正在刷新令牌的请求，允许刷新令牌
            refreshTokenComplete = false    // 将刷新标记改为false（代表正在刷新令牌）
            wx.request({
                header: {
                    Authorization: "Bearer " + getLoginToken(),
                    appid: appId,
                    'uni-platform': 'mp-weixin',
                },
                url:`${urlBase}/public/refreshToken`,
                method:"GET",
                success: (tokenRes) => {
                    if (tokenRes.data.error === 0){  // 刷新token成功
                        const token = tokenRes.data.token
                        // 设置新token
                        setLoginToken(token)
                        // 读取请求队列，并重新发送请求
                        requestQueues.forEach(callback => callback())
                        // 清空队列
                        requestQueues = []
                        // 重新发送当前请求
                        resolve(request(options))

                    }else{  // 刷新令牌失败
                        // 清空队列
                        requestQueues = []
                        // 退出登录
                        logout()
                        reject(tokenRes.data)
                    }
                },
                fail: (err) => {
                    //  请求失败
                    reject({
                        error: 9000,
                        msg: err.errMsg,
                    });
                },
                complete: () => {
                    refreshTokenComplete = true
                    console.log("刷新令牌完成", refreshTokenComplete)
                }
            })
        }else{	// 有正在刷新的令牌
            // 将请求加入队列
            requestQueues.push(() => {
                resolve(request(options))
            })
        }
    })

}
